package thread.juc_usage;

import java.util.concurrent.Semaphore;

public class SemaphoreTest {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(5);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getName()+"准备申请资源");
                    //P操作，默认申请一个资源
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"获取资源成功");
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName()+"释放资源");
                    //V操作默认释放一个占有的紫云
                    semaphore.release();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        };
        for (int i = 0; i < 20; i++) {
            Thread t = new Thread(runnable,String.valueOf(i+1));
            t.start();
        }
    }
}
